var modifyOrAddFlag;  // true表示新增，false表示修改
var arrayLi = [];
var arrayLiInd = 0;
//var fieldSystems=null;//保存获取的领域系统集合(减少访问数据库次数)
var treeData=null;//树结构数据
var g_currSystemsStr = "";
//初始化数据
$(document).ready(function(){
	//导入
	$('#import_link').window({
		width:465,
		modal:true,
		minimizable:false,
		maximizable:false,
		collapsible:false
	});
	$('#import_link').window('close');  //关闭窗口
	
	$('#winEdit').window('close');
	
	var urlParamObj = getParamobjFromUrl();
	var authState = urlParamObj.authState;
	$("#userForm .easyui-validatebox").blur(function() {
		$(this).validatebox("validate");
	});
	
	$("#selFileBtn").click(function(e){
		e.preventDefault();
		//$("#file").click();
	});

	$('input[plugin="passwordStrength"]').passwordStrength({minLen:1,maxLen:200});
	
	$("#import_form").delegate("#file" ,"change", function() {
	    $("#fileName").val($('#file').val());
	    //clearAutofillStyle();
	});
	
	$('#txtCreateTimeBeg').datetimebox({ 
		required : false,
		editable:false,
		onShowPanel:function(){ 
			$(this).datetimebox("spinner").timespinner("setValue","00:00:00"); 
		}
	});
	
	$('#txtCreateTimeEnd').datetimebox({ 
		required : false,
		editable:false,
		onShowPanel:function(){ 
			$(this).datetimebox("spinner").timespinner("setValue","23:59:59"); 
		}
	});
	
	$(".button_con a" ).removeClass("l-btn-plain");
	$('#comboxSearchCompany').combobox({
		editable: false,
		url: BASE_URL_USER_SEARCH +'/showOrganizations?level=1&v=' + Date.parse(new Date()),
		valueField: 'id',
		textField: 'orgName',
		method:'get',
		//data:"level=1",
		onSelect: function(record) {
			$("#comboxSearchCompany").val(record.id);
			$('#comboxSearchDepartment').combobox('clear');
			if(record.id == "")
			{
				$('#comboxSearchDepartment').combobox({
					disabled: true,
					url: ""
				});
			}
			else
			{
				$('#comboxSearchDepartment').combobox({
					disabled: false,
					url: BASE_URL_USER_SEARCH +'/showOrganizations?parentId='+record.id+'&level=2&v=' + Date.parse(new Date())
				});
			}
			
			//$('#comboxSearchDepartment').combobox('reload',BASE_URL_USER_SEARCH +'/showOrganizations?parentId='+record.id+'&level=2&v=' + Date.parse(new Date()));
			//console.log(record);
		},
		loadFilter:function(data){
			var allCheck = {'id':'','orgName':'全部', 'selected':true};
    		data.unshift(allCheck);
			return data;
		},
		onLoadSuccess: function() {
			//var defaultId = $("#comboxSearchCompany").combobox("getData")[0].id;
			//$("#comboxSearchCompany").combobox("select",defaultId);
		}
	    
	});
	
	$('#comboxSearchDepartment').combobox({
		disabled: true,
		editable: false,
		valueField: 'id',
		textField: 'orgName',
		method:'get',
		//data:"level=2",
		onSelect: function(record) {
			$("#comboxSearchDepartment").val(record.id);
			//console.log(record);
		},
		data: [{'id':'','orgName':'全部','selected':true}],
		loadFilter:function(data){
			var allCheck = {'id':'','orgName':'全部','selected':true};
    		data.unshift(allCheck);
			return data;
		},
		onLoadSuccess: function() {
			//var defaultId = $("#comboxSearchDepartment").combobox("getData")[0].id;
			//$("#comboxSearchDepartment").combobox("select",defaultId);
		}
	    
	});
	
	$('#roleId').combobox({
		editable: false,
		url: BASE_URL_ROLES + '?v=' + Date.parse(new Date()),
		valueField: 'id',
	    textField: 'roleName',
	    method:'get',
		onSelect: function(record) {
			$("#roleId").val(record.id);
			//console.log(record);
		},
	    loadFilter:function(data){
	    	return data._embedded.roles;
	    },
		onLoadSuccess: function() {
			if(!$("#roleId").val())
			{
				if(!modifyOrAddFlag)
				{
					return;
				}
				var dataList = $("#roleId").combobox("getData");
				var defaultId = dataList[0].id;
				for(var i = 0; i < dataList.length; ++i)
				{
					if(dataList[i].id == "1")
					{
						defaultId = dataList[i].id;
						break;
					}
				}
				$("#roleId").combobox("select",defaultId);
			}
			else
			{
				$("#roleId").combobox("setValue",$("#roleId").val());
			}
		}
	    
	});
	$('#comboxSearchAuthState').combobox({
		editable: false,
		valueField: 'id',
	    textField: 'name',
	    onSelect: function(record) {
			$("#comboxSearchAuthState").val(record.id);
	    },
	    data: [{
			"id": "",
			"name": "全部",
			"selected":authState == "unAuthorized"? false:true
		},{
			"id": "authorized",
			"name": "正常",
			"selected":authState == "authorized"? true:false
		},{
			"id": "unAuthorized",
			"name": "未授权",
			"selected":authState == "unAuthorized"? true:false
		}]
	    
	});
	$('#comboxAuthState').combobox({
		editable: false,
		disabled: true,
		valueField: 'id',
	    textField: 'name',
	    onSelect: function(record) {
			$("#comboxAuthState").val(record.id);
	    },
	    data: [{
			"id": "authorized",
			"name": "正常",
			"selected":true
		},{
			"id": "unAuthorized",
			"name": "未授权"
		}]
			    
	});
	$('#loginStatus').combobox({
		editable: false,
		valueField: 'id',
	    textField: 'name',
	    onSelect: function(record) {
			$("#loginStatus").val(record.id);
	    },
	    data: [{
			"id": "1",
			"name": "启用",
			"selected":true
		},{
			"id": "2",
			"name": "停用"
		}]
	});
	/*setTimeout(function(){
		var defaultId = $("#loginStatus").combobox("getData")[0].id;
		$("#loginStatus").combobox("select",defaultId);
	}, 1000);*/
	
	
	$('#companyCode').combobox({
		editable: false,
		url: BASE_URL_USER_SEARCH +'/showOrganizations?level=1&v=' + Date.parse(new Date()),
		valueField: 'id',
		textField: 'orgName',
		method:'get',
		//data:"level=1",
		onSelect: function(record) {
			$("#companyCode").val(record.id);
			$('#orgId').val("");
			$('#orgId').combobox('clear');
			$('#orgId').combobox({url:BASE_URL_USER_SEARCH +'/showOrganizations?parentId='+record.id+'&level=2&v=' + Date.parse(new Date())});
			//console.log(record);
		},
		loadFilter:function(data){
			return data;
		},
		onLoadSuccess: function() {
			if(!$("#companyCode").val())
			{
				var defaultId = $("#companyCode").combobox("getData")[0].id;
				$("#companyCode").val(defaultId);
				$("#companyCode").combobox("select",defaultId);
			}
			else
			{
				$("#companyCode").combobox("setValue",$("#companyCode").val());
			}
		}
	    
	});
	$('#orgId').combobox({
		editable: false,
		valueField: 'id',
		textField: 'orgName',
		method:'get',
		//data:"level=2",
		onSelect: function(record) {
			$("#orgId").val(record.id);
			//console.log(record);
		},
		loadFilter:function(data){
			return data;
		},
		onLoadSuccess: function() {
			if(!$("#orgId").val())
			{
				var defaultId = $("#orgId").combobox("getData")[0].id;
				$("#orgId").combobox("select",defaultId);
			}
			else
			{
				$("#orgId").combobox("setValue",$("#orgId").val());
			}
		}
	});
	
	
	$("#datagrid").datagrid({
		url : BASE_URL_USER_SEARCH +'/findByExample?v=' + Date.parse(new Date()),
		method:'get',
		autoRowHeight:true,//自动行高
		width:'100%',
		nowrap:false,
		singleSelect: true,//单选
		pagination:true,
		striped:true,
		pageSize:20,
		pageList:[10,20,50,100],
		columns:[[
					{field:'',width:10,checkbox:true},
					{field:'companyName',title:'公司',width:140},
					{field:'deptName',title:'部门',width:150},
					{field:'userCode',title:'账号',width:60,align:'left'},
					{field:'userName',title:'姓名',width:60,align:'left'},
					{field:'empNo',title:'工号',width:60},
					{field:'emailAddress',title:'邮箱地址',width:140,align:'left'},
					{field:'phoneNumber',title:'电话号码',width:100,align:'left'},					
					{field:'roleId',title:'授权状态',width:80, formatter: function(value, rowData, rowIndex){
							return !value?"未授权":"正常";
						}
					},
					{field:'loginStatus',title:'登录限制',width:60, formatter: function(value, rowData, rowIndex){
							return value == "1"?"启用":"停用";
						}
					},
					{field:'createTime',title:'注册时间',width:100},
					{field:'handle',title:'操作',width:60,  formatter: function(value, rowData, rowIndex){
						return '<a href="javascript:void(0)" class="default_btn" onclick="onOpenEdit(' + rowIndex + ');">授权</a>';
					}
				},
					{field:'remark',title:'备注',width:80,align:'left'},
					{field:'exeTimeOnDay',title:'异常日志接收时间',width:80,align:'left',hidden:true}
		      ]],
		loadFilter:function(data){
			return {
				total: data.totalElements,
				rows: data.content
			};
		},
		onSelect: function( rowIndex, rowData ) {
			if(rowData.loginStatus == "1")
			{
				$("#toolbar_start .l-btn-text").html("停用");
				$("#toolbar_start .icon-more").css("background","url(../../images/icons/stop.png) no-repeat center -1px"); 
			}
			else
			{
				$("#toolbar_start .l-btn-text").html("启用");
				$("#toolbar_start .icon-more").css("background","url(../../images/icons/restart.png) no-repeat center center"); 
			}
		},
		onUnselect: function()
		{
			$("#toolbar_start .l-btn-text").text("启用/停用");
			$("#toolbar_start .icon-more").css("background","url(../../images/icons/more.png) no-repeat center -1px"); 
		},
		onBeforeLoad:function(param){
			param.page -= 1;
			param.size = param.rows;
			param.sort = 'createTime,desc';
			param["beginOfCreateTime"] = $("#txtCreateTimeBeg").datetimebox('getValue');
			param["endOfCreateTime"] = $("#txtCreateTimeEnd").datetimebox('getValue');
			param["companyId"] = $("#comboxSearchCompany").combobox("getValue");
			param["orgId"] = $("#comboxSearchDepartment").combobox("getValue");
			param["emailAddress"] = $("#txtEmail").val();
			param["userName"] = $("#txtUserName").val();
			param["grantStatus"] = $('#comboxSearchAuthState').combobox("getValue");
			delete param.rows;

		}
	});
	
	$("#datagrid").datagrid('getPager').pagination({   
	    displayMsg:'当前显示从 [{from}] 到 [{to}] 共[{total}]条记录'
		}); 

		
});

function onSave()
{
	$("#instance_save").linkbutton("disable");
	$("#instance_save .l-btn-text").text("提交中...");
	if($("#userForm").form("validate")){
		if(modifyOrAddFlag)
		{
			RegistUser();
		}
		else
		{
			ModifyUserInfo();
		}
	}
    else 
    {
    	$("#instance_save").linkbutton("enable");
		$("#instance_save .l-btn-text").text("保存");
    	$(".validatebox-invalid").eq(0).focus();
    }
}
function onAdd()
{
	
	modifyOrAddFlag = true;
	$("#userForm input[type='password']").parent().parent().show();
	$("#userCode").removeAttr("readonly");
	$("#userForm .input_con > input").each(function(){
		if(!$(this).hasClass("combobox-f"))
		{
			$(this).val("");
		}
	});
	$('#loginStatus').combobox('select', "1");
	$('#comboxAuthState').combobox('select', "authorized");

	$('#roleId').combobox('clear');
	$('#roleId').combobox({
		disabled: false,
		url: BASE_URL_ROLES + '?v=' + Date.parse(new Date())
	});
	
	$(".passwordStrength > span").removeClass("bgStrength");
	
	var exeTimeOnDay = $('#comboxExecutionExeTimeOnDay').combobox('getData');
	$("#comboxExecutionExeTimeOnDay").combobox('setValue',exeTimeOnDay[0].value);
	
	setTimeout(function(){
		$("#comboxExecutionExeTimeOnDay").siblings(".textbox").children(".textbox-text").val($("#comboxExecutionExeTimeOnDay").combobox('getText'));
	},50);
	
	/*$("#userForm")[0].reset();
	
	var data = $('#loginStatus').combobox('getData');
	$('#loginStatus').combobox('clear');
	$('#loginStatus').combobox('loadData', data);
	
	$('#role').combobox('clear');
	$('#role').combobox('reload',BASE_URL_ROLES + '?v=' + Date.parse(new Date()));
	
	$('#companyCode').combobox('clear');
	$('#companyCode').combobox('reload',BASE_URL_USER_SEARCH +'/showOrganizations?level=1&v=' + Date.parse(new Date()));
	*/
	$("#userForm").form("validate");
	
	$("#winEdit").window('setTitle','用户信息管理-新增');
	$('#winEdit').window('open');
}

function RegistUser() {
	var userInfoJSON = $("#userForm").serializeJson();
	userInfoJSON["password"] = RSAUtils.encryptedString(key,userInfoJSON["password"]);
	userInfoJSON["confirmPassword"] = "";
	delete userInfoJSON["confirmPassword"];
	userInfoJSON["exeTimeOnDay"]=$('#comboxExecutionExeTimeOnDay').combobox('getValue');
	/*
	userInfoJSON["role"] = BASE_URL_ROLES + '/' + userInfoJSON["role"];
	userInfoJSON["organization"] = BASE_URL_ORGANIZATION+'/'+ userInfoJSON["organization"];*/
	$.ajax({
		type: "post",
		url: BASE_URL_USER_CRUD +'/administratorAddUser',
		data: JSON.stringify(userInfoJSON),
		contentType: "application/json",
		success: function(result) {
			$("#instance_save").linkbutton("enable");
			$("#instance_save .l-btn-text").text("保存");
			if(result.backValue === true)
			{
				$('#winEdit').window('close');
				$.messager.alert('提示','<p>新增用户成功!</p>', 'info');
				setTimeout(function(){
					$("#datagrid").datagrid("reload", BASE_URL_USER_SEARCH + '/findByExample?v=' + Date.parse(new Date()));
				}, 100);
			}
			else
			{
				$.messager.alert('错误','<p>添加用户失败，' + result.backValue + '</p>', 'error');
			}
		},
		error: function() {
			$("#instance_save").linkbutton("enable");
			$("#instance_save .l-btn-text").text("保存");
			$.messager.alert('错误','<p>服务异常，新增用户失败，请稍后重试!</p>', 'error');
		}
	});
}

function ModifyUserInfo() {
	var row = $('#datagrid').datagrid('getSelected');
	var newUserInfoJSON = $("#userForm").serializeJson();
	newUserInfoJSON["exeTimeOnDay"]=$('#comboxExecutionExeTimeOnDay').combobox('getValue');
	newUserInfoJSON["id"] = row.id;
	$.ajax({
		type: "post",
		url: BASE_URL_USER + "/administratorUpdateUser",
		data: JSON.stringify(newUserInfoJSON),
		contentType: "application/json",
		success: function(result) {
			$("#instance_save").linkbutton("enable");
			$("#instance_save .l-btn-text").text("保存");
			if(result.backValue === true)
			{
				//如果修改的是当前用户，则更新页面上的当前用户信息
				if(window.parent.g_currUserCode == newUserInfoJSON["userCode"])
				{
					window.parent.GetCurrUserInfo();
				}
				$('#winEdit').window('close');  //关闭窗口
				$.messager.alert('提示','<p>修改用户资料成功!</p>', 'info');
				$("#datagrid").datagrid("reload", BASE_URL_USER_SEARCH + '/findByExample?v=' + Date.parse(new Date()));
			}
			else
			{
				$.messager.alert('错误','<p>修改用户资料失败，' + result.backValue + '</p>', 'error');
			}
		},
		error: function() {
			$("#instance_save").linkbutton("enable");
			$("#instance_save .l-btn-text").text("保存");
			$.messager.alert('错误','<p>服务异常，修改用户资料失败，请稍后重试!</p>','error');
		}
	});
}

function onUpdate() {
	var row = $('#datagrid').datagrid('getSelected');
	if(row == null){
		$.messager.alert('警告',"<p>请选中要修改的记录</p>", "warning");
	}else{
		modifyOrAddFlag = false;
		$("#userForm input[type='password']").parent().parent().hide();
		$("#userCode").attr("readonly", true);
		SetFormData($("#userForm"), row);
		$("#confirmPassword").val(row.password);
		$('#roleId').val(row.roleId);
		$('#companyCode').val(row.companyId);
		$('#orgId').val(row.deptId);

		$('#loginStatus').combobox('select', row.loginStatus);

		$('#comboxAuthState').combobox('select', !row.roleId? "unAuthorized":"authorized");
		
		$('#roleId').combobox('clear');
		if(window.parent.g_currUserCode == row.userCode && row.roleId == "0")
		{
			$('#roleId').combobox({
				disabled: true,
				onBeforeLoad: function() {
					$("#roleId").val(row.roleId);
				},
				url: BASE_URL_ROLES + '?v=' + Date.parse(new Date())
			});
		}
		else
		{
			$('#roleId').combobox({
				disabled: false,
				onBeforeLoad: function() {
					$("#roleId").val(row.roleId);
				},
				url: BASE_URL_ROLES + '?v=' + Date.parse(new Date())
			});
		}
		
		$('#companyCode').combobox('clear');
		$('#companyCode').combobox('reload',BASE_URL_USER_SEARCH +'/showOrganizations?level=1');
		
		$('#orgId').combobox('clear');
		$('#orgId').combobox('reload',BASE_URL_USER_SEARCH +'/showOrganizations?parentId='+row.companyId+'&level=2');

		$("#comboxExecutionExeTimeOnDay").combobox('setValue',row.exeTimeOnDay);
		//$("#userCode").val(row.userCode);
		$("#userForm").form("validate");
		
		$("#winEdit").window('setTitle','用户信息管理-修改');
		$('#winEdit').window('open');
	}
}

function onDel() {
	var row = $('#datagrid').datagrid('getSelected');
	if(row == null){
		$.messager.alert('警告',"<p>请选中要删除的用户</p>", "warning");
		return;
	}
	//如果选中的是当前用户，则阻止删除当前用户
	if(window.parent.g_currUserCode == row.userCode)
	{
		$.messager.alert('警告',"<p>不能删除自己喔!</p>", "warning");
		return;
	}
	$.messager.confirm('温馨提示','你真的要删除么?',function(result){
		if (result){
			delUser();
		}
	});
}

function delUser() {
	var row = $('#datagrid').datagrid('getSelected');
	var userInfoJson = {};
	userInfoJson["id"] = row.id;
	$.ajax({
		url:BASE_URL_USER_CRUD + '/deleteUser?v=' + Date.parse(new Date()),
		dataType:'json',
		type:'delete',
		data: JSON.stringify(userInfoJson),
		async:false,
		contentType:"application/json",
		timeout:30000,
		success:function(result){
			if(result.backValue === true)
			{
				$.messager.alert('提示',"<p>删除成功!</p>", "info");
				//$('#datagrid').datagrid('deleteRow',$('#datagrid').datagrid('getRowIndex', row));
				$("#datagrid").datagrid("reload", BASE_URL_USER_SEARCH + '/findByExample?v=' + Date.parse(new Date()));
			}
			else
			{
				$.messager.alert('错误',"<p>删除用户失败！" + result.backValue + "</p>","error");
			}
		},
		error:function(xhr,s,err){
			$.messager.alert('错误',"<p>删除用户失败!</p>","error");
		}
	});
}

function setEnable() {
	var row = $('#datagrid').datagrid('getSelected');
	if(row == null){
		$.messager.alert('提示',"<p>请选中所要操作的用户</p>", 'info');
		return;
	}
	var jsonData = {
			id: row.id,
			loginStatus:row.loginStatus == "1"? "2":"1"
	};
	$.ajax({
		type: "post",
		url: BASE_URL_USER + "/startOrStopUserLoginStatus",
		data: JSON.stringify(jsonData),
		contentType: "application/json",
		success: function(result) {
			if(result.backValue === true)
			{
				$('#winEdit').window('close');  //关闭窗口
				$.messager.alert('提示','<p>' + $("#toolbar_start .l-btn-text").html() + '用户成功!</p>', "info");
				$("#toolbar_start .l-btn-text").html("启用");
				$("#datagrid").datagrid("reload", BASE_URL_USER_SEARCH + '/findByExample?v=' + Date.parse(new Date()));
			}else{
				$.messager.alert('错误',"<p>" + $("#toolbar_start .l-btn-text").html() + "用户失败！" + result.backValue + "</p>","error");
			}
		},
		error: function() {
			$.messager.alert('错误','<p>服务异常，' + $("#toolbar_start .l-btn-text").html() + '用户失败，请稍后重试!</p>','error');
		}
	});
}

function rePage(){
	$('#winEdit').window('close');
}

function onSearch(){
	dataRetrieval('#txtCreateTimeBeg','#txtCreateTimeEnd');
}

//导入
function import_link()
{
	$('#import_link').window('open'); 
}

function startImport() {
	if($("#file").val() == "")
	{
		$.messager.alert("警告", "<p>请选择需要导入的.xls或.xlsx格式的文件</p>", 'warning');
		return;
	}
	var tempArr = $("#file").val().split(".");
	var selFileType = tempArr[tempArr.length - 1];
	if(selFileType != "xls" && selFileType != "xlsx")
	{
		$.messager.alert("警告", "<p>选择的文件格式有误，请选择.xls或.xlsx格式的文件</p>", 'warning');
		return;
	}
	$("#buttons_inport .easyui-linkbutton").linkbutton("disable");
	$("#buttons_inport .l-btn-text").text("正在导入...");
 		
	//$("#import_form").submit();
	$.ajaxFileUpload({
        url: '/api/importData/user/userUpload' + "?name=" + encodeURI($("#fileName").val()), 
        type: 'post',
        secureuri: false, //一般设置为false
        fileElementId: 'file', // 上传文件的id、name属性名
        dataType: 'text', //返回值类型，一般设置为json、application/json
        //data: "name=" + encodeURI($("#fileName").val()), //传递参数到服务器
        success: function(data, status){
        	
     		$("#buttons_inport .easyui-linkbutton").linkbutton("enable");
     		$("#buttons_inport .l-btn-text").text("确定导入");
     		
        	//var resultObj = eval("[" + data.activeElement.innerText + "]")[0];
        	var resultObj = JSON.parse(data.slice(data.indexOf(">") + 1,data.indexOf("</")));
            if(resultObj.backValue === true)
            {
	            $("#fileName").val($('#file').val());
            	$('#import_link').window('close'); 
            	$("#datagrid").datagrid("reload", BASE_URL_USER_SEARCH + '/findByExample?v=' + Date.parse(new Date()));
            	$.messager.alert('提示',"<p>导入成功！</p>", 'info');
            }
            else if(resultObj.backValue === false)
            {
	            $("#fileName").val($('#file').val());
            	$.messager.alert('错误',"<p>导入失败!所选文件内容为空或存在异常！</p>","error");
            }
            else
            {
	            $("#fileName").val($('#file').val());
            	$.messager.alert('错误',"<p>导入失败！" + resultObj.backValue + "</p>", "error"); 
            }
        },
        error: function(data, status, e){ 
            $("#fileName").val($('#file').val());
     		$("#buttons_inport .easyui-linkbutton").linkbutton("enable");
     		$("#buttons_inport .l-btn-text").text("确定导入");
     		
        	$.messager.alert('错误',"<p>导入失败!</p>","error");
        }
    });
}

//设置表单数据，data对象里个字段名必须与表单里个输入元素的id对应一致，若data为空，则将表单置空
function SetFormData($form, data) {
	$("input,select", $form).each(function() {
		var $input = $(this);
		if($input.attr("id"))
		{
			if(data)
			{
				$input.val(data[$input.attr("id")]);
			}
			else
			{
				$input.val("");
			}
		}
	});
}

